<?php

namespace app\index\controller;

use app\BaseController;
use app\index\model\CommentModel;
use app\index\model\CommentReplyModel;
use app\index\model\CommentLike as CommentLikeModel;
use app\index\model\Notice as NoticeModal;
use app\index\validate\CommentValidate;
use app\index\diyclass\Task;
use app\Request;
use think\facade\Db;

class Comment  extends BaseController
{
    protected $middleware = [
        'Auth' => ['except' => ['imageComment', 'list', 'detail', 'childer']],
        'Openness' => ['only' => ['imageComment', 'list', 'detail', 'childer']],
    ];
    public function imageComment(Request $request)
    {
        $params = $this->request->post(['photoId', 'imageId']);
        $commentSql = new CommentModel();
        if(!empty($request->user)) {
            $user = $request->user;
            $list = $commentSql
                ->where('exchangeId', $params['photoId'])
                ->where('imageId', $params['imageId'])
                ->where('type', 4)
                ->with(['userInfo'])
                ->withCount([
                    'reply',
                    'like',
                    'likeNum' => function($query) use($user) { $query->where('userId', $user['id']); },
                ])
                ->order('like_count desc')
                ->order('create_at desc')
                ->select();
            foreach ($list as $item) {
                $item->isLike = $item->like_num_count > 0 ? true : false;
                unset($item->like_num_count);
            }
        } else {
            $list = $commentSql
                ->where('exchangeId', $params['photoId'])
                ->where('imageId', $params['imageId'])
                ->where('type', 4)
                ->with(['userInfo'])
                ->withCount([
                    'reply',
                    'like',
                ])
                ->order('like_count desc')
                ->order('create_at desc')
                ->select();
            foreach ($list as $item) {
                $item->isLike = false;
            }
        }
//        $oss = new OssService();
//        foreach ($list as $key => $value) {
//            if($value->userInfo->comment_bg_id) {
//                $value->userInfo->commentBg =  $oss->signId($value->userInfo->comment_bg_id);
//            }
//        }
        return result()->success($list);
    }
    public function commentCount()
    {
        $params = $this->request->post(['photoId', 'type']);
        $commentSql = new CommentModel();
        $count = $commentSql
            ->where('exchangeId', $params['photoId'])
            ->where('type', $params['type'])
            ->count();
        return result()->success($count);
    }
    public function list(Request $request) {
        $params = $this->request->post(['current', 'size', 'photoId', 'type']);
        $commentSql = new CommentModel();
        try {
            if(!empty($request->user)) {
                $user = $request->user;
                $list = $commentSql
                    ->where('exchangeId', $params['photoId'])
                    ->where('type', $params['type'])
                    ->page($params['current'])
                    ->limit($params['size'])
                    ->with(['userInfo'])
                    ->withCount([
                        'reply',
                        'like',
                        'likeNum' => function($query) use($user) { $query->where('userId', $user['id']); },
                    ])
                    ->order('like_count desc')
                    ->order('create_at desc')
                    ->select();
                foreach ($list as $item) {
                    $item->isLike = $item->like_num_count > 0 ? true : false;
                    unset($item->like_num_count);
                }
            } else {
                $list = $commentSql
                    ->where('exchangeId', $params['photoId'])
                    ->where('type', $params['type'])
                    ->page($params['current'])
                    ->limit($params['size'])
                    ->with(['userInfo'])
                    ->withCount([
                        'reply',
                        'like',
                    ])
                    ->order('like_count desc')
                    ->order('create_at desc')
                    ->select();
                foreach ($list as $item) {
                    $item->isLike = false;
                }
            }
            return result()->success($list);
        } catch (\Throwable $th) {
            return result()->fail($th->getMessage(), 500);
        }
    }
    public function detail(Request $request)
    {
        $params = $this->request->post(['id']);
        $commentSql = new CommentModel();
        if(!empty($request->user)) {
            $user = $request->user;
            $info = $commentSql
                ->where('id', $params['id'])
                ->with(['userInfo'])
                ->withCount([
                    'reply',
                    'like',
                    'likeNum' => function($query) use($user) { $query->where('userId', $user['id']); },
                ])
                ->find();
            $info->isLike = $info->like_num_count > 0 ? true : false;
        } else {
            $info = $commentSql
                ->where('id', $params['id'])
                ->with(['userInfo'])
                ->withCount([
                    'reply',
                    'like',
                ])
                ->find();
            $info['isLike'] = false;
        }
//        if($info->userInfo->comment_bg_id) {
//            $oss = new OssService();
//            $info->userInfo->commentBg =  $oss->signId($info->userInfo->comment_bg_id);
//        }
        return result()->success($info);
    }

    public function childer(Request $request) {
        $params = $this->request->post(['id']);
        $sql = new CommentReplyModel();
        if(!empty($request->user)) {
            $user = $request->user;
            $list = $sql
                ->where('commentId', $params['id'])
                ->with(['userInfo', 'fatherUserInfo', 'fatherInfo'])
                ->withCount([
                    'like',
                    'likeNum' => function($query) use($user) { $query->where('userId', $user['id']); }
                 ])
                ->order('create_at asc')
                ->order('like_count desc')
                ->select();
            foreach ($list as $item) {
                $item->isLike = $item->like_num_count > 0 ? true : false;
                unset($item->like_num_count);
            }
        } else {
            $list = $sql
                ->where('commentId', $params['id'])
                ->with(['userInfo', 'fatherUserInfo', 'fatherInfo'])
                ->withCount([
                    'like'
                ])
                ->order('create_at asc')
                ->order('like_count desc')
                ->select();
            foreach ($list as $item) {
                $item->isLike = false;
                unset($item->like_num_count);
            }
        }
//        $oss = new OssService();
//        foreach ($list as $key => $value) {
//            if($value->userInfo->comment_bg_id) {
//                $value->userInfo->commentBg =  $oss->signId($value->userInfo->comment_bg_id);
//            }
//        }
        return result()->success($list);
    }

    public function doLike(Request $request) {
        $params = $this->request->post(['id', 'type']);
        $validate = new CommentValidate();
        if (!$validate->scene('like')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $user = $request->user;
        $sql = new CommentLikeModel();
        $info = $sql
            ->where('relevancyId', $params['id'])
            ->where('userId', $user->id)
            ->where('type', $params['type'])
            ->select();
        if ($info->isEmpty()) {
            $sql->save([
                'relevancyId' => $params['id'],
                'type' => $params['type'],
                'userId' => $user->id,
            ]);
            return result()->success(true);
        } else {
            $info->delete();
            return result()->success(true);
        }
    }

    public function submit(Request $request) {
        $params = $this->request->post(['exchangeId', 'imageId', 'content', 'type']);
        $validate = new CommentValidate();
        if (!$validate->scene('addComment')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        Db::startTrans();
        try {
            $this->userinfo = $request->user;
            $commentSql = new CommentModel();
            $user = $request->user;
            $commentSql->save([
                "userId" => $user->id,
                "exchangeId" => $params['exchangeId'],
                "imageId" => $params['imageId'],
                "type" => $params['type'],
                "content" => $params['content'],
            ]);
            $newInfo = $commentSql
                ->where('id', $commentSql->id)
                ->with(['userInfo'])
                ->find();
            $task = new Task($user->id, 'COMMENT');
            $task->save();
            Db::commit();
            $newInfo['reply_count'] = 0;
            $newInfo['like_count'] = 0;
            $newInfo['isLike'] = false;
            return result()->success($newInfo);
        } catch (\Throwable $th) {
            Db::rollback();
            return result()->fail($th->getMessage(), 500);
        }
    }

    public function replySubmit(Request $request) {
        $params = $this->request->post(['id', 'content', 'isMore']);
        $validate = new CommentValidate();
        if (!$validate->scene('reply')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        Db::startTrans();
        try {
            $commentSql = new CommentReplyModel();
            $user = $request->user;
            if(empty($params['isMore'])) {
                $params['isMore'] = false;
            }
            $arr = [
                "userId" => $user['id'],
                "commentId" => $params['id'],
                "content" => $params['content'],
                "sort" => 0,
            ];
            if($params['isMore']) {
                $info = $commentSql->find($params['id']);
                $arr['fatherid'] = $info->id;
                $arr['fatherUserId'] = $info->userId;
                $arr['commentId'] = $info->commentId;
                $info->sort = $info->sort + 10;
                $info->save();
            } else {
                $sql = new CommentModel();
                $info = $sql->find($params['id']);
            }
            $commentSql->save($arr);
            $newInfo = $commentSql
                ->where('id', $commentSql->id)
                ->with(['userInfo', 'fatherUserInfo', 'fatherInfo'])
                ->find();
            $noticeSql = new NoticeModal();
            $noticeSql->save([
                "type" => "REPLY_EXCHANGE",
                "userId" => $info->userId,
                "content" => $user->nickname."回复了你:".$params['content'],
                "association" => $newInfo['id'],
                'otherUserid' => $user->id
            ]);
            $task = new Task($user->id, 'COMMENT_TASK');
            $task->save();
            Db::commit();
            $newInfo['reply_count'] = 0;
            $newInfo['like_count'] = 0;
            $newInfo['isLike'] = false;
            return result()->success($newInfo);
        } catch (\Throwable $th) {
            Db::rollback();
            return result()->fail($th->getMessage(), 500);
        }
    }
}